<template>
  <v-card class="upload-dialog" flat>
    <v-spacer class="upload-content-wrap pa-2">
      <v-col class="header d-flex justify-space-between pa-0">
        <span class="title px-3">
          <slot name="title">
            {{ syncedItem.itemNumber }}- {{ syncedItem.itemDescription }}
          </slot>
        </span>
        <div>
          <slot name="header.append"></slot>
        </div>
      </v-col>
      <v-col class="pa-0 pt-2">
        <v-card class="images-wrap" height="660" flat no-gutters>
          <div v-if="step === 1">
            <v-spacer
              v-for="(attachment, index) in syncedItem.attachment
                .attachmentList"
              :key="attachment.date"
              :class="{ vacancies: [0, 1].includes(index) }"
            >
              <v-col class="text-left px-0 py-1">
                {{ attachment.date }}
              </v-col>
              <v-col class="pa-0">
                <div class="images clearfix">
                  <v-row no-gutters>
                    <v-col
                      class="image-wrap flex-grow-0"
                      v-for="file in attachment.fileList"
                      :key="file.id"
                    >
                      <v-checkbox
                        v-model="selectedFiles"
                        :value="file"
                        class="checkbox"
                        color="#556282"
                        hide-details
                        off-icon="mdi-checkbox-blank"
                      ></v-checkbox>
                      <img
                        @click="showViewAttachment(attachment, file)"
                        v-if="file.ext === 'jpg' || file.ext === 'png'"
                        :alt="file.fileName"
                        :src="file.src"
                        class="image"
                      />
                      <span v-else>
                        {{ file.fileName }}
                      </span>
                    </v-col>
                  </v-row>
                </div>
              </v-col>
            </v-spacer>
            <v-card
              v-if="step === 1"
              class="product-photo-box"
              flat
              width="200px"
              height="200px"
            >
              <div class="image-wrap">
                <v-img
                  v-if="syncedItem.attachment.productPhoto"
                  :src="syncedItem.attachment.productPhoto"
                  height="100%"
                ></v-img>
              </div>
              <v-tooltip bottom>
                <template v-slot:activator="{ on }">
                  <v-file-input
                    v-on="on"
                    @change="uploadProductPhoto"
                    accept="image/*"
                    class="upload-btn"
                    hide-input
                    prepend-icon="mdi-image-area"
                    truncate-length="15"
                  >
                  </v-file-input>
                </template>
                Upload Product Photo
              </v-tooltip>
            </v-card>
          </div>
          <v-spacer
            v-else-if="step === 2 && viewFile && currentAttachment"
            class="pa-0"
          >
            <v-col class="text-left pb-0">
              {{ currentAttachment.date }}
            </v-col>
            <v-col>
              <ViewAttachment
                :attachment="viewFile"
                :title="viewFile.fileName"
              ></ViewAttachment>
            </v-col>
          </v-spacer>
        </v-card>
      </v-col>
      <v-col class="upload-wrap px-0 pt-4 pb-2">
        <v-file-input
          v-if="step === 1"
          @change="uploadFile"
          accept="image/*"
          class="upload-btn"
          hide-input
          multiple
          prepend-icon="mdi-upload"
          truncate-length="15"
        >
        </v-file-input>
      </v-col>
    </v-spacer>
  </v-card>
</template>

<script lang="ts">
import { Vue, Component, PropSync } from "vue-property-decorator";
import { getDate } from "@/common/constants/Utils";
import ViewAttachment from "@/components/Project/Upload/ViewAttachment.vue";
import { IAttachment, IFile, IItemsItem } from "@/components/Customer/index";
import { readerFile } from "@/common/constants/Utils";
import VFileInput from "vuetify/src/components/VFileInput";
type VFileInputInstance = InstanceType<typeof VFileInput>;

@Component({
  components: {
    ViewAttachment,
  },
})
export default class Upload extends Vue {
  @PropSync("item", {
    type: Object,
    default: () => ({}),
  })
  syncedItem!: IItemsItem;

  get dialogTitle() {
    return this.step === 1 ? "" : "View Attachment";
  }

  viewFile: IFile | null = null;
  currentAttachment: IAttachment | null = null;

  showViewAttachment(attachment: IAttachment, file: IFile) {
    this.viewFile = file;
    this.currentAttachment = attachment;
    this.step = 2;
  }

  step = 1;

  clickFileInput() {
    (this.$refs.fileInput as VFileInputInstance).$refs.input.click();
  }

  async uploadFile(files: HTMLInputElement["files"]) {
    if (!files || files.length <= 0) return;
    for (let i = 0; i < files.length; i++) {
      const currentAttachment = this.syncedItem.attachment.attachmentList.find(
        (item) => {
          return item.date === getDate("-");
        }
      );
      const file = files[i];
      const reader: FileReader = await readerFile(file);
      if (!reader.error) {
        // 文件转base64成功
        const fileName = file.name;
        const lastIndex = fileName.lastIndexOf(".");
        const ext = fileName.substring(lastIndex + 1).toLowerCase();
        console.log(reader.result);
        const fileObj = {
          id: `${new Date().getTime()}${file.name}`,
          ext: ext,
          src: reader.result as string,
          fileName: file.name,
        };
        if (currentAttachment) {
          currentAttachment.fileList.push(fileObj);
        } else {
          const attachment = {
            id: String(new Date().getTime()),
            number: "DL-20211209001",
            date: getDate("-"),
            fileList: [fileObj],
          };
          this.syncedItem.attachment.attachmentList.push(attachment);
        }
      } else {
        // 文件转base64失败
        this.SweetAlertService.error("Upload Error");
      }
    }
  }

  async uploadProductPhoto(file: File) {
    const reader: FileReader = await readerFile(file);
    if (!reader.error) {
      // 文件转base64成功
      this.syncedItem.attachment.productPhoto = reader.result as string;
    } else {
      // 文件转base64失败
      this.SweetAlertService.error("Upload Error");
    }
  }

  selectedFiles: IFile[] = [];

  deleteFile() {
    const viewFile = this.viewFile;
    if (this.step === 2 && viewFile && this.currentAttachment) {
      const viewFileIndex = this.currentAttachment.fileList.indexOf(viewFile);
      this.currentAttachment.fileList.splice(viewFileIndex, 1);
      this.viewFile = null;
      this.currentAttachment = null;
      this.$emit("close");
      this.step = 1;
    } else if (this.step === 1) {
      this.selectedFiles.forEach((file) => {
        this.syncedItem.attachment.attachmentList.forEach((attachment) => {
          const fileIndex = attachment.fileList.indexOf(file);
          attachment.fileList.splice(fileIndex, 1);
        });
      });
      this.selectedFiles = [];
    }
  }

  downloadFile() {
    if (this.step === 1) {
      this.selectedFiles.forEach((file) => {
        this.download(file.src, file.fileName);
      });
    } else if (this.step === 2) {
      if (this.viewFile) {
        this.download(this.viewFile.src, this.viewFile.fileName);
      }
    }
  }

  download(url: string, fileName: string) {
    fetch(url).then((res) => {
      res.blob().then((blob) => {
        const aTag = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        aTag.href = href;
        aTag.download = fileName;
        aTag.click();
      });
    });
  }
  close() {
    if (this.step === 1) {
      this.$emit("close");
    } else if (this.step === 2) {
      this.step = 1;
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/components/Project/Upload/Upload.scss";
@import "@/components/Customer/Dialog/Attachment/Attachment.scss";
</style>
